package com.github.authcloud.server.configure.filter.gateway;

import com.github.authcloud.common.NoRequiresLoginMapping;
import com.github.authcloud.common.RequiresRolePermissionMapping;
import com.github.authcloud.server.configure.AuthRolePermissionLocalCache;
import com.github.authcloud.server.configure.checker.UserAuthRolePermission;
import com.github.authcloud.server.configure.exception.NoLoginException;
import com.github.authcloud.server.configure.exception.NoRolePermissionException;
import com.github.authcloud.server.configure.properties.AuthCommonProperties;
import com.github.authcloud.server.configure.utils.AuthRolePermissionMatchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : zhaoxuan
 * @version : 1.0
 * @date : 2021/8/22 14:47
 * @description : GatewayAuthRolePermissionFilter
 */
public class GatewayAuthRolePermissionFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserAuthRolePermission userAuthRolePermission;

    @Resource
    private AuthCommonProperties authCommonProperties;

    @Override
    public int getOrder() {
        return RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER - 1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        String method = request.getMethodValue();
        Route route =(Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        String serviceName = route.getId().replace("ReactiveCompositeDiscoveryClient_", "");

        if (!shouldFilter(uri)) {
            return chain.filter(exchange);
        }

        List<NoRequiresLoginMapping> noRequiresLoginMappings = AuthRolePermissionLocalCache.getNoLoginMapping(serviceName);
        boolean authIsPast = AuthRolePermissionMatchUtil.isInNoLoginMappings(uri, method, noRequiresLoginMappings);
        if (!authIsPast && !userAuthRolePermission.isLogin()) {
            throw new NoLoginException("access this api required authentication");
        }
        List<RequiresRolePermissionMapping> requiresRolePermissionMappings = AuthRolePermissionLocalCache.getRolesPermissionMapping(serviceName);
        RequiresRolePermissionMapping rolesPermission = AuthRolePermissionMatchUtil.getRequiresRolesPermissionsMapping(uri, method, requiresRolePermissionMappings);
        if (rolesPermission == null) {
            return chain.filter(exchange);
        }
        boolean roleCheckIsPass = AuthRolePermissionMatchUtil.checkRoles(userAuthRolePermission.getRoles(), rolesPermission.getRoles(), rolesPermission.getRolesLogical());
        if (!roleCheckIsPass) {
            throw new NoRolePermissionException("access this api required roles " + rolesPermission.getRoles().toString());
        }
        boolean permissionsCheckIsPass = AuthRolePermissionMatchUtil.checkPermissions(userAuthRolePermission.getPermissions(), rolesPermission.getPermissions(), rolesPermission.getPermissionsLogical());
        if (!permissionsCheckIsPass) {
            throw new NoRolePermissionException("access this api required permissions " + rolesPermission.getPermissions().toString());
        }
        return chain.filter(exchange);
    }


    private boolean shouldFilter(String uri){
        if (!authCommonProperties.getNotInterApiPrefix().isEmpty()) {
            return authCommonProperties.getNotInterApiPrefix().stream()
                    .map(notInterApiPreFix -> notInterApiPreFix.replaceAll("\\*", ""))
                    .noneMatch(uri::startsWith);
        }
        if (!authCommonProperties.getInterApiPrefix().isEmpty()) {
            return authCommonProperties.getInterApiPrefix().stream()
                    .map(interApiPrefix -> interApiPrefix.replaceAll("\\*", ""))
                    .anyMatch(uri::startsWith);
        }
        return true;
    }
}
